'''
Created on Jan 18, 2010

@author: madsk
'''

from __future__ import with_statement
from PIL import Image
import os
from PyQt4 import QtGui
import StringIO
from imageprocessing.imageops import scale 
from scavenger import Scavenger
from scavenger_common import RemoteDataHandle

class MultiImage(object):
    def __init__(self, path=None, size=None):
        super(MultiImage, self).__init__()
        self._preview = None
        self._pixmap = None
        self._path = path
        self._size = size
        
        if path != None and size != None:
            self.loadFromFile(path, size)
        
    def loadFromFile(self, path, desired_size):
        # Set properties.
        self._path = path
        self._size = desired_size
        
        # Create the preview version if necessary.
        preview_path = path + '.preview'
        if os.path.exists(preview_path):
            self._preview = Image.open(preview_path)
        else:
            with open(path, 'r') as infile:
                original = infile.read()
            preview = scale(original, desired_size)
            if type(preview) == RemoteDataHandle:
                preview = Scavenger.fetch_data(preview)
            with open(preview_path, 'w') as outfile:
                outfile.write(preview)
            self._preview = Image.open(preview_path)
            
        # Load pixmap version.
        self._previewToPixmap()
    
    def _previewToPixmap(self):
        file = StringIO.StringIO()
        self._preview.save(file, 'ppm')
        contents = file.getvalue()
        file.close()
        self._pixmap = QtGui.QPixmap()
        self._pixmap.loadFromData(contents)
        
    def original(): #@NoSelf
        def fget(self):
            return Image.open(self._path)
        return locals()
    original = property(**original())    
        
    def preview(): #@NoSelf
        def fget(self):
            return self._preview
        def fset(self, value):
            self._preview = value
            self._previewToPixmap()
        def fdel(self):
            del self._preview
        return locals()
    preview = property(**preview())
    
    def pixmap(): #@NoSelf
        def fget(self):
            return self._pixmap
        return locals()
    pixmap = property(**pixmap())
    
    def path(): #@NoSelf
        def fget(self):
            return self._path
        return locals()
    path = property(**path())
